package cn.xshi.gateway.route.client;

import cn.xshi.gateway.route.client.handler.GatewayNettyClientHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.context.ApplicationEventPublisher;

/**
 * @Desc 服务器网关路由通道初始化
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
public class GatewayNettyClientInitializer extends ChannelInitializer<SocketChannel> {

    private GatewayNettyClient gatewayNettyClient;

    private String clientId;//客户端id（每个服务对应一个客户端唯一id）

    private String clientGroupId;//组Id（可以存多个服务共享一个组Id）

    private ApplicationEventPublisher applicationEventPublisher;

    public GatewayNettyClientInitializer(){

    }

    public GatewayNettyClientInitializer(GatewayNettyClient gatewayNettyClient, String clientGroupId, String clientId,ApplicationEventPublisher applicationEventPublisher){
        this.gatewayNettyClient = gatewayNettyClient;
        this.clientGroupId = clientGroupId;
        this.clientId = clientId;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        /*
        socketChannel.pipeline().addLast(new JsonMessageDecoder());
        socketChannel.pipeline().addLast(new JsonMessageEncoder());
        socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
        */

        //ProtobufVarint32LengthFieldPrepender，ProtobufVarint32FrameDecoder解决大字符串粘包、拆包问题
        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
        socketChannel.pipeline().addLast(new ProtobufEncoder());
        socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast(new GatewayNettyClientHandler(gatewayNettyClient,clientGroupId,clientId,applicationEventPublisher));
    }
}